<script setup>
import { onMounted, onUnmounted, ref } from 'vue'
import Recorder from 'recorder-core';
import 'recorder-core/src/engine/mp3'
import 'recorder-core/src/engine/mp3-engine'
import axios from 'axios'
const status = ref('wait')

var rec;

var recBlob;


const props = defineProps({
    userId1: Number,
    userId2: Number
})


function recOpen() {
    //创建录音对象
    rec = Recorder({
        type: "mp3" //录音格式，可以换成wav等其他格式
        , sampleRate: 12000 //录音的采样率，越大细节越丰富越细腻
        , bitRate: 16 //录音的比特率，越大音质越好
        , onProcess: (buffers, powerLevel, bufferDuration, bufferSampleRate, newBufferIdx, asyncEnd) => {
            //录音实时回调，大约1秒调用12次本回调
            //可实时绘制波形，实时上传（发送）数据
            // if(this.wave) this.wave.input(buffers[buffers.length-1],powerLevel,bufferSampleRate);
        }
    });

    //打开录音，获得权限
    rec.open(() => {
        console.log("录音已打开");
        // if(this.$refs.recwave){//创建音频可视化图形绘制对象
        // 	this.wave=Recorder.WaveView({elem:this.$refs.recwave});
        // }
    }, (msg, isUserNotAllow) => {
        //用户拒绝了录音权限，或者浏览器不支持录音
        console.log((isUserNotAllow ? "UserNotAllow," : "") + "无法录音:" + msg);
    });
}

function recStart() {
    if (!rec) { console.error("未打开录音"); return }
    rec.start();
    console.log("已开始录音");
}

function recStop() {
    if (!rec) { console.error("未打开录音"); return }
    rec.stop((blob, duration) => {
        //blob就是我们要的录音文件对象，可以上传，或者本地播放
        recBlob = blob;
        //简单利用URL生成本地文件地址，此地址只能本地使用，比如赋值给audio.src进行播放，赋值给a.href然后a.click()进行下载（a需提供download="xxx.mp3"属性）
        var localUrl = (window.URL || webkitURL).createObjectURL(blob);
        console.log("录音成功", blob, localUrl, "时长:" + duration + "ms");

        // rec.close();//关闭录音，释放录音资源，当然可以不释放，后面可以连续调用start
        // rec = null;
    }, (err) => {
        console.error("结束录音出错：" + err);
        rec.close();//关闭录音，释放录音资源，当然可以不释放，后面可以连续调用start
        rec = null;
    });
}

function upload(blob) {
    //使用FormData用multipart/form-data表单上传文件
    //或者将blob文件用FileReader转成base64纯文本编码，使用普通application/x-www-form-urlencoded表单上传
    var form = new FormData();
    let timeString = new Date().toISOString()
    console.log(timeString);
    form.append("multipartFile", blob, timeString + ".mp3"); //和普通form表单并无二致，后端接收到upfile参数的文件，文件名为recorder.mp3
    form.append("sendUserId", props.userId1); //其他参数
    form.append("receiveUserId", props.userId2)
    form.append("messageType", "voice")
    axios.post('https://47.120.69.214:8787/chat/sendMessageToUser', form, {///发送请求
        headers: {
            'Content-Type': 'multipart/form-data'//设置请求头
        }
    });

}

function recPlay() {
    //本地播放录音试听，可以直接用URL把blob转换成本地播放地址，用audio进行播放
    var localUrl = URL.createObjectURL(recBlob);
    var audio = document.createElement("audio");
    audio.controls = true;
    document.body.appendChild(audio);
    audio.src = localUrl;
    audio.play(); //这样就能播放了

    //注意不用了时需要revokeObjectURL，否则霸占内存
    setTimeout(function () { URL.revokeObjectURL(audio.src) }, 5000);
}

function startRecord() {
    console.log("startRecord");
    // recOpen()
    recStart()
    status.value = "recording"
}

function endRecord() {
    recStop()
    status.value = "end"
}

function sendAudio() {
    upload(recBlob);//把blob文件上传到服务器
    status.value = 'wait'
}

function listen() {
    let localUrl = URL.createObjectURL(recBlob);
    let music = new Audio(localUrl)
    music.play()
}

function cancel() {
    status.value = "wait"
}

onMounted(() => recOpen())
onUnmounted(() => {
    rec.close()
    rec = null
})
</script>

<template>
    <div>
        <el-card shadow="always" :body-style="{ padding: '20px' }">
            <div v-if="status == 'wait'">
                <el-button type="primary" size="default" @click="startRecord">开始录音</el-button>
            </div>
            <div v-if="status == 'recording'">
                <el-button type="primary" size="default" @click="endRecord">结束录音</el-button>
            </div>
            <div v-if="status == 'end'">
                <el-button type="primary" size="default" @click="sendAudio">发送录音</el-button>
                <el-button type="primary" size="default" @click="listen">试听</el-button>
                <el-button type="danger" size="default" @click="cancel">取消</el-button>
            </div>
        </el-card>
    </div>
</template>